package logic

import (
	"context"
	"errors"
	"pro-train-hub/models/cache"
	"pro-train-hub/models/mysql"
	"pro-train-hub/pkg"

	"pro-train-hub/trainrpc/internal/svc"
	"pro-train-hub/trainrpc/trainrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPwdLogic {
	return &ForgetPwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForgetPwdLogic) ForgetPwd(in *trainrpc.ForgetPwdRequest) (*trainrpc.ForgetPwdResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("该用户不存在")
	}
	captchaCode, _ := cache.RDB.Get(l.ctx, "captcha"+in.Mobile).Result()
	if captchaCode != in.CaptchaCode {
		return nil, errors.New("图形验证码有误，请重新输入")
	}

	smsCode, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if smsCode != in.SmsCode {
		return nil, errors.New("短信验证码有误，请重新输入")
	}

	if in.NewPassword != in.NewPassword2 {
		return nil, errors.New("两次密码输入不一致")
	}

	user.Password = pkg.Md5string(in.NewPassword)
	mysql.DB.Debug().Updates(&user)
	return &trainrpc.ForgetPwdResponse{
		UserId: int64(user.ID),
	}, nil
}
